package com.runchinaup.smartbelt.activity;


import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.runchinaup.runchilibrary.modes.activity.RootActivity;
import com.runchinaup.runchilibrary.upg.DownloadProgressDialog;
import com.runchinaup.runchilibrary.upg.Messager;
import com.runchinaup.runchilibrary.upg.UpgHelper;
import com.runchinaup.runchilibrary.upg.core.NetCallback;
import com.runchinaup.runchilibrary.upg.rcu.LocalVersionInfo_2;
import com.runchinaup.runchilibrary.upg.rcu.RCUParser;
import com.runchinaup.runchilibrary.upg.rcu.RCURespData;
import com.runchinaup.smartbelt.R;
import com.runchinaup.smartbelt.audioRecord.AudioRecordDemo;
import com.runchinaup.smartbelt.ble.BlueGattCallbackHelper;
import com.runchinaup.smartbelt.domian.AlarmCanData;
import com.runchinaup.smartbelt.domian.BleData;
import com.runchinaup.smartbelt.domian.BleDevice;
import com.runchinaup.smartbelt.preferences.AlarmCanInfoPre;
import com.runchinaup.smartbelt.preferences.ConnSelfPre;
import com.runchinaup.smartbelt.preferences.ModernDeviceInfoPro;
import com.runchinaup.smartbelt.view.CircleMenuLayout;
import com.runchinaup.smartbelt.view.pop.ListPop;
import com.xw.repo.BubbleSeekBar;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by liber on 2018/1/18.
 */

/**
 * 蓝牙点击关闭，来电，短信，闹钟，同步时钟
 */

public class IndexActivity extends RootActivity implements View.OnClickListener, BlueGattCallbackHelper.OnCallBackListener {

    private TextView centerText;
    private TextView callText;
    private TextView messageText;
    private TextView alarmText;
    private TextView looseText;
    private TextView timeText;
    private TextView strongText;
    //图片资源
    private ImageView openOrClose;
    private ImageView alarmImage;
    private ImageView messageImage;
    private ImageView callImage;
    private ImageView looseImage;
    //底下的强度，时间的bar
    private BubbleSeekBar timeBar;
    private BubbleSeekBar strongBar;
    //六个圆环的布局
    private CircleMenuLayout circleMenuLayout;
    //保存用户使用的数据，  一个是圆环的数据，一个底下三个按钮
    private SharedPreferences shared;
    private SharedPreferences textShared;
    private SharedPreferences.Editor textEditor;
    private SharedPreferences.Editor mEditor;
    //点击的是第几个圆环
    private String bluetoothPosition;
    //用于发送数据的类，记录了用户的操作
    private BleData bleData = new BleData();
    //用于判断连接成功没有，如果没有连接成功返回null，成功则返回操作类
    private boolean isConnect;
    //蓝牙对象的操作
    private BlueGattCallbackHelper gattCallbackHelper = BlueGattCallbackHelper.getBlueGattCallbackHelper();
    //用于记录下半圆的文字
    private TextView circleText;
    //判断是否在扫描
    private boolean isScan = false;
    //监听周围的声音（音贝）
    private AudioRecordDemo audio;

    //圆环的上半圆的图片，下半圆的文字显示。
    private String[] textView;
    private int[] image = new int[]{R.mipmap.bluetooth, R.mipmap.bluetooth, R.mipmap.bluetooth, R.mipmap.bluetooth, R.mipmap.bluetooth, R.mipmap.bluetooth};
    protected float[] backgroundAlphas = new float[]{0.6f, 0.6f, 0.6f, 0.6f, 0.6f, 0.6f};
    //设置重新连接的时间 毫秒为单位  十分钟
    private int reConnTime = 10 * 60000;
    //连接成功的地址，也用于保存
    private HashMap<String, String> connMac;
    //自动重连
    private Handler connHandler;
    //自动连接时的提示对话框
    private ProgressDialog connectDialog;
    //震动
    private Vibrator vibrator;

    @Override
    public int loadLayout() {
        return R.layout.page_1;
    }

    @Override
    public void initView() {
        initLayoutView();
        //记录设备的信息
        initSharedPreferences();
        //圆环的点击监听
        makeCircleClick();
        //档位的调节监听
        makeProgressChange();
        //在线更新
        initDialog();
        cfgAppUpgrade();
        //注册监听
        gattCallbackHelper.resigistBlueCallback(this);
        //初始化handler
        initHandler();
        //取得之前连接过的设备mac地址
        connMac = ConnSelfPre.read(this);
        if (connMac == null) {
            connMac = new HashMap<>();
        } else {
            Log.e("initView: size", connMac.size() + "");
            if (connMac.size() > 0) {
                //打开app自动连接
                Iterator iter = connMac.entrySet().iterator();
                while (iter.hasNext()) {
                    HashMap.Entry entry = (HashMap.Entry) iter.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    Log.e("initView: mac", value);
                    gattCallbackHelper.setDisDevice(new BleDevice("ZNCP", value));
                }
                Log.e("initView: ", gattCallbackHelper.getDisDevice().size() + "");
                if (bluetoothAdapter.isEnabled()) {
                    connHandler.sendEmptyMessage(0);
                    connectDialog.show();
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            connectDialog.cancel();
                        }
                    }, 5000);
                }
            }
        }

        initDefaultImage();
        //监听周围的声音
        initAudioVolume();

        initModernDevice();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //离开这个界面就停止自动连接
        connHandler.sendEmptyMessage(1);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        gattCallbackHelper.resigistBlueCallback(this);
        makeCircleClick();
        //回到这个界面，就检查有没有设备断连
        if (gattCallbackHelper.getDisDevice().size() > 0) {
            connHandler.sendEmptyMessage(0);
        }
        readAlarm();
        for (int i = 0; i < 6; i++) {
            if (gattCallbackHelper.isConnect(i + "")) {
                image[i] = R.mipmap.link;
                backgroundAlphas[i] = 1.0f;
                circleMenuLayout.setMenuResource(image, textView, backgroundAlphas);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //杀死app前，将停止所有设备
        bleData.setOpenClose(true);
        makeCenterClick();
        //关闭周围声音的监听
        audio.closeAudio();
        //停止扫描周围的设备W
        connHandler.sendEmptyMessage(1);
    }

    //连接完成后的反馈
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 333) {
            if (data != null) {
                if (gattCallbackHelper.isConnect(bluetoothPosition)) {
                    String mac = data.getStringExtra("bleMac");
                    if (!connMac.containsValue(mac))
                        connMac.put(bluetoothPosition, mac);
                    Log.e("onResult: position", bluetoothPosition);
                    ConnSelfPre.save(this, connMac);
                    setCircleColor(1);
                } else {
                    toast(R.string.link_fail);
                }
            } else {
                Log.e("onActivityResult: ", "intent is null");
            }
        }
    }

    //蓝牙设备的回调
    @Override
    public void linkCall(String bluetoothPosition, BleDevice bleDevice) {
    }

    //蓝牙设备状态的回调
    @Override
    public void onState(int state, final String bluetoothPosition, final BleDevice bleDevice) {
        //1说明连接成功，减少对应的一个。。。已经全部连接上的时候，停止扫描...最后一个延迟8秒后停止扫描
        if (state == 1) {
            Log.e("onState: success", gattCallbackHelper.getDisDevice().size() + "");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int position = Integer.parseInt(bluetoothPosition);
                    image[position] = R.mipmap.link;
                    backgroundAlphas[position] = 1.0f;
                    circleMenuLayout.setMenuResource(image, textView, backgroundAlphas);
                }
            });
            gattCallbackHelper.removeDisDevice(bleDevice);
            if (gattCallbackHelper.getDisDevice().size() == 0) {
                connHandler.sendEmptyMessage(1);
                Log.e("onState: finish", "link_finish");
                connectDialog.cancel();
            }
        }
        if (state == 2) {
        }

    }

    //设备电量的回调
    @Override
    public void getElectricity(byte[] data) {
        if (data != null) {
            Log.e("ElectricityData", String.format("%02d", (data[9] & 0xff)));
            final String bluetoothElectrivity = String.format("%02d", (data[9] & 0xff));
            //获取设备电量后，传递给popwindow
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ListPop.getPop(IndexActivity.this, bluetoothElectrivity).showPicker($View(R.id.page1_layout)
                            , circleText.getText().toString().trim()
                            , new ListPop.ListPopClickCallback() {
                                @Override
                                public void onSelect(final String tvContent) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            circleText.setText(tvContent);
                                            textEditor.putString(bluetoothPosition, tvContent);
                                            textEditor.commit();
                                        }
                                    });
                                }

                                @Override
                                public void chooseModern() {
                                    //现代理疗模式，添加
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            gattCallbackHelper.addModernDevice(bluetoothPosition);
                                            Log.e("run: addModern", gattCallbackHelper.getModernDevice().size() + "");
                                            ModernDeviceInfoPro.save(IndexActivity.this, gattCallbackHelper.getModernDevice());
                                            toastLong(R.string.use_microphone);
                                        }
                                    });
                                }

                                @Override
                                public void chooseTradition() {
                                    //传统模式，删除
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            gattCallbackHelper.removeModernDevice(bluetoothPosition);
                                            Log.e("run: delectModern", gattCallbackHelper.getModernDevice().size() + "");
                                            ModernDeviceInfoPro.save(IndexActivity.this, gattCallbackHelper.getModernDevice());
                                            toast(R.string.use_hand);
                                        }
                                    });
                                }
                            });
                }
            });


        } else {
            Log.e("ElectricityData", "is null");
            toast(R.string.get_ble_data_fail);
        }
    }

    @Override
    public void onExceptionDis(final String bluetoothPosition, final BleDevice device) {

//        Log.e("onExceptionDis", gattCallbackHelper.getDisDevice().size() + "");
        int position = Integer.parseInt(bluetoothPosition);
        image[position] = R.mipmap.no_link;
        backgroundAlphas[position] = 0.6f;

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                circleMenuLayout.setMenuResource(image, textView, backgroundAlphas);
                gattCallbackHelper.removeDeviceList(bluetoothPosition);
                if (shared.getBoolean("isLoose", false)) {
                    vibrator.vibrate(500);
                }
            }
        });

        if (gattCallbackHelper.getDisDevice().size() > 0) {
            connHandler.sendEmptyMessage(0);
            toast(R.string.re_linking);
//            Log.e("onExceptionDis", "linking");
        }
    }

    @Override
    public void getAlarmCan(byte[] data) {

    }

    @Override
    public void getAlarmTime(byte[] data) {

    }

    //点击中间四个按钮的监听(防丢失、来电、来信、闹钟)
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //防丢失
            case R.id.phone_loose_text:
            case R.id.phone_loose_image:
                makePhoneLoose();
                break;
            //来电
            case R.id.phone_call_text:
            case R.id.phone_call_image:
                makePhoneCall();
                break;
            //来信
            case R.id.message_text:
            case R.id.message_image:
                makePhoneMessage();
                break;
            //闹钟
            case R.id.alarm_text:
            case R.id.alarm_image:
                makePhoneAlarm();
                break;
            //中间的开始或者暂停的按钮
            case R.id.close_open:
                makeCenterClick();
                break;
            default:
                break;
        }
    }

    //读取用户设定的现代模式下的设备
    private void initModernDevice() {
        ArrayList<String> list = ModernDeviceInfoPro.read(this);
        if (list != null) {
            Log.e("initModernDevice: ", list.size() + "");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    gattCallbackHelper.addModernDevice(list.get(i));
                }
            }
        }
    }

    //初始化监听周围音贝，回调收到的音贝
    private void initAudioVolume() {
        audio = new AudioRecordDemo(new AudioRecordDemo.AudioCallback() {
            @Override
            public void volumeData(double data) {
                if (gattCallbackHelper.hadConnect()) {       //至少要有设备连接
                    makeBleWork(data);
                    setBleDataByModern();
                }
            }
        });
    }

    private void makeBleWork(double data) {

        double added = (78.00 - 58.00) / 10;
        //数据大于70，设置为70
        data = data >= 77 ? 77 : data;
        bleData.setTimeData((byte) 1);
        if (data > 58) {
            //当在范围内，减去最小值再除以增值。就可以获得模式的值对
            int result = (int) ((data - 58) / added);
            bleData.setStrongData((byte) result);
        } else {
            bleData.setTimeData((byte) 0);
        }
        Log.e("makeBleWork: ", bleData.getStrongData() + "");
    }


    //设置来电提醒、短信提醒、防丢失的默认图片
    private void initDefaultImage() {
        boolean isMessage = shared.getBoolean("isMessage", false);
        setMessageImage(isMessage);
        boolean isCall = shared.getBoolean("isCall", false);
        setPhoneImage(isCall);
        boolean isLoose = shared.getBoolean("isLoose", false);
        setPhoneLoose(isLoose);
        readAlarm();
    }

    private void initSharedPreferences() {

        //判断是不是有点击三个按钮  是否防丢失，是否来电提醒，是否短信提醒
        shared = getSharedPreferences("buttonIsOpen", MODE_PRIVATE);
        mEditor = shared.edit();

        //6个圆环的内容
        textShared = getSharedPreferences("textView", MODE_PRIVATE);
        textEditor = textShared.edit();
//        textEditor.commit();

        textView = new String[]{
                textShared.getString(0 + "", $str(R.string.page1_one)),
                textShared.getString(1 + "", $str(R.string.page1_two)),
                textShared.getString(2 + "", $str(R.string.page1_three)),
                textShared.getString(3 + "", $str(R.string.page1_four)),
                textShared.getString(4 + "", $str(R.string.page1_five)),
                textShared.getString(5 + "", $str(R.string.page1_six))
        };
    }

    private void initLayoutView() {
        centerText = $View(R.id.centerText);
        centerText.setText(R.string.app_name);

        strongBar = $View(R.id.bar_strong);
        timeBar = $View(R.id.bar_time);

        strongText = $View(R.id.page1_strong_text);
        timeText = $View(R.id.page1_time_text);

        circleMenuLayout = $View(R.id.circle_menu);

        openOrClose = $View(R.id.close_open);
        looseText = $View(R.id.phone_loose_text);
        callText = $View(R.id.phone_call_text);
        messageText = $View(R.id.message_text);
        alarmText = $View(R.id.alarm_text);

        looseImage = $View(R.id.phone_loose_image);
        messageImage = $View(R.id.message_image);
        callImage = $View(R.id.phone_call_image);
        alarmImage = $View(R.id.alarm_image);

        openOrClose.setOnClickListener(this);
        looseText.setOnClickListener(this);
        callText.setOnClickListener(this);
        messageText.setOnClickListener(this);
        alarmText.setOnClickListener(this);
        looseImage.setOnClickListener(this);
        callImage.setOnClickListener(this);
        messageImage.setOnClickListener(this);
        alarmImage.setOnClickListener(this);

        //设置时间和强度的默认值
        int strong = bleData.getStrongData();
        int time = bleData.getTimeData();
        strongBar.setProgress(strong);
        timeBar.setProgress(time);
        strongText.setText(String.format("%01d/10", strong));
        timeText.setText(String.format("%01d/10", time));

        connectDialog = new ProgressDialog(this);
        connectDialog.setCanceledOnTouchOutside(true);
        connectDialog.setCancelable(false);
        connectDialog.setMessage($str(R.string.is_link));

        //获取系统的震动
        vibrator = (Vibrator) getSystemService(this.VIBRATOR_SERVICE);

    }

    //判断有没有打开蓝牙，没有不给进去使用
    private boolean blueisOpen() {
        if (!bluetoothAdapter.isEnabled()) {
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
            return false;
        } else return true;
    }


    //中心圆环的点击事件
    private void makeCenterClick() {
        if (gattCallbackHelper.hadConnect()) {      //是否设备连接的判断
            bleData.setOpenClose(!bleData.isOpenClose());
            if (bleData.isOpenClose()) {
                openOrClose.setImageResource(R.mipmap.button_close);
                //开始监听周围的声音
                audio.getNoiseLevel();
            } else {
                openOrClose.setImageResource(R.mipmap.button_open);
                //关闭获取周围声音
                audio.closeAudio();
                setBleDataByModern();
            }
            setBleData();
        } else {
            toast(R.string.please_link);
        }
    }

    //圆环的点击事件
    private void makeCircleClick() {
        circleMenuLayout.setMenuResource(image, textView, backgroundAlphas);
        circleMenuLayout.setOnMenuClickListener(new CircleMenuLayout.OnMenuClickListener() {
            //点击圆环的上半圆
            @Override
            public void onMenuClick(int position, ImageView imageView, RelativeLayout relativeLayout, TextView textView1) {
                bluetoothPosition = position + "";
                Log.e("position", bluetoothPosition + "");
                //判断对应圆环是否有设备连接   返回true 或者false
                isConnect = gattCallbackHelper.isConnect(bluetoothPosition);
                if (!isConnect) {
                    circleSwitch(0);
                } else {
                    gattCallbackHelper.unLink(bluetoothPosition);
                    toast(R.string.unlink);
                    setCircleColor(0);
                    circleMenuLayout.setMenuResource(image, textView, backgroundAlphas);
                    connMac.remove(position + "");
                    ConnSelfPre.save(IndexActivity.this, connMac);
                }
            }

            //点击圆环的下半圆
            @Override
            public void onTextClick(int position, TextView textView) {
                circleText = textView;
                bluetoothPosition = position + "";
                //判断对应圆环是否有设备连接     返回true 或者false
                isConnect = gattCallbackHelper.isConnect(bluetoothPosition);
                if (!isConnect) {
                    circleSwitch(0);
                } else {
                    circleSwitch(1);
                }


            }
        });
    }


    //圆环上下两部分的点击事件  0是上部分 1是下部分   正常没连接过的走0，进去连接界面
    private void circleSwitch(int i) {

        Intent intent = new Intent(this, ScanActivity.class);
        intent.putExtra("bluetoothPosition", bluetoothPosition);

        if (blueisOpen()) {
            switch (i) {
                case 0:     //进入扫描界面
                    startActivityForResult(intent, 000);
                    break;
                case 1:     //获取设备电池电量，然后打开popwindow
                    gattCallbackHelper.sendForElectricity(bluetoothPosition);
                    break;
            }
        } else {
            toast(R.string.please_open_blue);
        }
    }

    //圆环颜色的改变     0代表浅色，1代表深色  0就是没有连接，1就是已经连接
    private void setCircleColor(int i) {
        switch (i) {
            case 0:
                int one = Integer.parseInt(bluetoothPosition);
                image[one] = R.mipmap.no_link;
                backgroundAlphas[one] = 0.6f;
                break;
            case 1:
                int two = Integer.parseInt(bluetoothPosition);
                image[two] = R.mipmap.link;
                backgroundAlphas[two] = 1.0f;
                break;
        }
    }

    //动态设置蓝牙设备的时间和强度
    private void makeProgressChange() {
        //调节强度的监听  传递参数给蓝牙
        strongBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                strongText.setText(progress + "/10");
                progress = progress - 1;
                bleData.setStrongData((byte) progress);
                if (gattCallbackHelper.hadConnect()) {
                    if (bleData.isOpenClose()) {
                        setBleData();
                    }
                }
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
            }
        });
        //调节时间的监听
        timeBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                timeText.setText(progress + "/10");
                bleData.setTimeData((byte) progress);
                if (gattCallbackHelper.hadConnect()) {
                    if (bleData.isOpenClose()) {
                        setBleData();
                    }
                }
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

            }
        });
    }


    //设置蓝牙数据        向蓝牙设备发送数据(传统模式)
    private void setBleData() {
        if (gattCallbackHelper.hadConnect()) {
            bleData.setModelData((byte) 3);
            bleData.setTimeData((byte) 1);
            gattCallbackHelper.ControllBle(bleData);
        }
    }

    //设置蓝牙数据        向蓝牙设备发送数据(现代模式)
    private void setBleDataByModern() {
        if (gattCallbackHelper.hadConnect()) {
            bleData.setModelData((byte) 6);
            gattCallbackHelper.ControllBleByModern(bleData);
        }
    }


    //闹钟提醒
    private void makePhoneAlarm() {
        if (gattCallbackHelper.hadConnect()) {
            jump(AlarmActivity.class);
        } else {
            toast(R.string.please_link);
        }
//        jump(AlarmActivity.class);
    }

    private void readAlarm() {
        AlarmCanData alarmCanData = AlarmCanInfoPre.read(this);
        if (alarmCanData != null) {
            setAlarmImage(alarmCanData.alarmIsOpen());
        } else {
            setAlarmImage(false);
        }
    }

    private void setAlarmImage(boolean isAlarm) {
        if (isAlarm) {
            alarmImage.setImageResource(R.mipmap.alarm_open);
            alarmText.setTextColor(getResources().getColor(R.color.title_background));
        } else {
            alarmImage.setImageResource(R.mipmap.alarm_close);
            alarmText.setTextColor(getResources().getColor(R.color.button_text_color));
        }
    }

    //短信提醒
    private void makePhoneMessage() {
        if (gattCallbackHelper.hadConnect()) {
            boolean isMessage = shared.getBoolean("isMessage", false);
            isMessage = !isMessage;
            setMessageImage(isMessage);
            Log.e("makePhoneMessage: ", isMessage + "");
            mEditor.putBoolean("isMessage", isMessage);
            mEditor.commit();
        } else {
            toast(R.string.please_link);
        }
    }

    private void setMessageImage(boolean isMessage) {
        if (isMessage) {
            messageImage.setImageResource(R.mipmap.message_open);
            messageText.setTextColor(getResources().getColor(R.color.title_background));
        } else {
            messageImage.setImageResource(R.mipmap.message_close);
            messageText.setTextColor(getResources().getColor(R.color.button_text_color));
        }
    }

    //来电提醒
    private void makePhoneCall() {
        if (gattCallbackHelper.hadConnect()) {
            boolean isCall = shared.getBoolean("isCall", false);
            isCall = !isCall;
            Log.e("makePhoneCall: ", isCall + "");
            setPhoneImage(isCall);      //设置图片颜色
            mEditor.putBoolean("isCall", isCall);
            mEditor.commit();
        } else {
            toast(R.string.please_link);
        }
    }

    //设置来电提醒的图片
    private void setPhoneImage(boolean isCall) {
        if (isCall) {
            callImage.setImageResource(R.mipmap.phone_call_open);
            callText.setTextColor(getResources().getColor(R.color.title_background));
        } else {
            callImage.setImageResource(R.mipmap.phone_call_close);
            callText.setTextColor(getResources().getColor(R.color.button_text_color));
        }
    }

    //手机防丢
    private void makePhoneLoose() {
        if (gattCallbackHelper.hadConnect()) {
            boolean isLoose = shared.getBoolean("isLoose", false);
            isLoose = !isLoose;
            Log.e("makePhoneLoose: ", isLoose + "");
            setPhoneLoose(isLoose);
            mEditor.putBoolean("isLoose", isLoose);
            mEditor.commit();
            gattCallbackHelper.phoneLoose();
        } else {
            toast(R.string.please_link);
        }
    }

    private void setPhoneLoose(boolean isLoose) {
        if (isLoose) {
            looseImage.setImageResource(R.mipmap.phone_open);
            looseText.setTextColor(getResources().getColor(R.color.title_background));
        } else {
            looseImage.setImageResource(R.mipmap.phone_close);
            looseText.setTextColor(getResources().getColor(R.color.button_text_color));
        }
    }


    //初始化handler
    private void initHandler() {

        connHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    Log.e("handleMessage: ", "startScan");
                    startScan();
                    connHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            connHandler.sendEmptyMessage(1);
                        }
                    }, reConnTime);
                }
                if (msg.what == 1) {
                    stopScan();
                }
            }
        };
    }

    //开始扫描
    private void startScan() {
        if (!isScan) {
            bluetoothAdapter.startLeScan(reConnCallback);
            isScan = true;
        }
        Log.e("startScan: ", "is scan");
//            bluetoothAdapter.startLeScan(reConnCallback);
    }

    //停止扫描
    private void stopScan() {
        bluetoothAdapter.stopLeScan(reConnCallback);
        isScan = false;
        Log.e("stopScan: ", "is stop");
    }


    //用于重新连接的扫描
    final BluetoothAdapter.LeScanCallback reConnCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            Iterator iter = connMac.entrySet().iterator();
            while (iter.hasNext()) {
                HashMap.Entry entry = (HashMap.Entry) iter.next();
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                if (value.equals(device.getAddress())) {
                    Log.e("onLeScan: ", device.getAddress());
                    gattCallbackHelper.linkBle(key, new BleDevice("ZNCP", value), IndexActivity.this);
                }

            }

        }
    };


    /*********************************************************************************/

    //以下在线更新
    UpgHelper<RCURespData> helper = null;

    private DownloadProgressDialog progressDialog = null;

    private void cfgAppUpgrade() {
        //先把本地的app解析，如果是3段的就选择LocalVersionInfo_3
        final RCUParser<LocalVersionInfo_2> rcuParser = new RCUParser<LocalVersionInfo_2>() {
            @Override
            public boolean isEnableUpg(RCURespData rcuRespData, LocalVersionInfo_2 localVersionInfo_2) {
                return localVersionInfo_2.enableUpdate(localVersionInfo_2, localVersionInfo_2.parser(rcuRespData.getData().get(0).getVersion()));
            }

            @Override
            public LocalVersionInfo_2 parserFromLocal() {
                return LocalVersionInfo_2.parser(LocalVersionInfo_2.getVersionName(getUI()));
            }
        };

        String upgUrl = "http://www.runchinaup.com/app_upload/index.php/home/index/getfirmware?name=SmartBelt";

        //实例化升级助手
        helper = UpgHelper.getInstance(this);
        helper.getLastAppInfo(upgUrl, rcuParser, new NetCallback<RCURespData>() {
            @Override
            public void onResponse(final RCURespData net, String result) {
                Log.e("debug_net", net.getData().toString());
//                Log.e("debug_version===>net:",
//                        net.getData().getVersion() + "=local:" + rcuParser.parserFromLocal().getVersionStr());
                if (rcuParser.isEnableUpg(net, rcuParser.parserFromLocal())) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AlertDialog alert = new AlertDialog.Builder(getUI()).setTitle(R.string.upg_tips)
                                    .setMessage(getString(R.string.upg_find_last_version) + net.getData().get(0).getVersion())
                                    .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            progressDialog.showDialog().updataPro("0");
                                            helper.downLoad(net, new Messager<RCURespData>() {
                                                @Override
                                                public long returnFileSize(RCURespData rcuRespData) {
                                                    return Long.valueOf(net.getData().get(0).getSize());
                                                }

                                                @Override
                                                public String returnDownloadUrl(RCURespData rcuRespData) {
                                                    return net.getData().get(0).getDownload_url();
                                                }
                                            }, new UpgHelper.DownloadCallback() {
                                                @Override
                                                public void onPrgress(final float pro) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            progressDialog.updataPro(String.format("%.2f%%", pro));
                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onFinish(File newAppFile) {
                                                    helper.toInstall(newAppFile);
                                                }

                                            });

                                        }
                                    })
                                    .setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            // 点击“返回”后的操作,这里不设置没有任何操作
                                        }
                                    }).show();
                            alert.setCanceledOnTouchOutside(false);
                            alert.setCancelable(false);
                        }
                    });
                }
            }
        });
    }

    private void initDialog() {
        if (progressDialog == null) {
            progressDialog = new DownloadProgressDialog(this) {

                @Override
                public void onLeftClick() {
                    super.onLeftClick();
                    helper.cancel();
                }

                @Override
                public void onRightClick() {
                    super.onRightClick();
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(intent);
                }
            };
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }
    }
}
